<?php
namespace control;
/*
*附近客户类
*/

class vicinityClientClass extends adIndexClass
{
    private const title = '附近客户';
    private const page = 'vicinityClient';
    private const table = 'kehu';
    public const EARTH_RADIUS = 6378.137;

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $array = [
            [
                [
                    L('vicinityClient.home.companyName') => text(array("name" => "companyName")).hidden(array('name' => 'range', 'value' => 10)),
                    L('vicinityClient.home.label')   => text(array("name" => "label")),
                    L('vicinityClient.home.contactName') => text(array("name" => "contactName")),
                ],
                [
                    L('vicinityClient.home.contactTel')  => text(array("name" => "contactTel")),
                    L('vicinityClient.home.landline')  => text(array("name" => "landline")),
                    L('vicinityClient.home.workFlow')  => select(array("name" => "workFlow", "option" => explode("，", para("clientWorkFlow")))),
                ],
                [
                    L('vicinityClient.home.source')  => select(array("name" => "source", "option" => explode("，", para("clientSource")))),
                    L('vicinityClient.home.text')  => text(array("name" => "text")),
                    L('vicinityClient.home.time')  => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ];
        if ($this->power('client','seeAll')){
            $array[0][] = [
                L('vicinityClient.home.seeType') => select(array("name" => "seeType", 'value'=>L('vicinityClient.home.seeAll'),"option" => ['查看自己'=>L('vicinityClient.home.see'),'查看全部'=>L('vicinityClient.home.seeAll')]))
            ];
        }
        //生成查询表单
        $html = $this->tableShow($array,1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 查询条
     * @return string
     */
    public function home(): string
    {
        $root = root;
        $key = para('tencentMapKey');
        $center = para('centerPoint');
        $vicinityDistance = para('vicinityDistance');
        $style = $this->style();
        $search = "
                <div class='list-top'>
                    <div class='top-left'>
                        <div class='left-search'>
                            <div class='search-switch'>查询</div>
                            <div class='search-container'>
                                <div class='search-back'></div>
                                <div class='search-div'>
                                    <form name='searchForm' onsubmit='return false;'>
                                        <div class='search-input-list'>
                                            " . $this->homeOptions(false) . "
                                        </div>
                                        <div class='search-hidden'></div>
                                        <div class='search-buttons'>
                                            <input class='layer_search_button' type='submit' id='searchButton' value='" . lang('button.search') . "'>
                                            <span class='cancel-button'>取消</span>
                                            <span class='reset-button' onclick=\"searchResetting(this, 'vicinityClient','homeOptions', {});\">重置</span>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class='top-right'>
                        <div class='right-button'>
                        </div>
                    </div>
                </div>
                ";
        $queryWord = L('vicinityClient.home.query');
        $setCenterPointWord = L('vicinityClient.home.setCenterPoint');
        $sureWord = L('vicinityClient.home.sure');
        $centerPointWord = L('vicinityClient.home.centerPoint');
        $html = <<<efo

<div style="width: 100%;height: 100%;background-color: #F2F2F2">
{$search}
<div style="padding-top: 10px">
<div class="left-content">
<img alt="" id="no-data-ico" style="display: none" src="{$root}img/control/department-no.svg">
<ul id="left-content-ul">

</ul>

</div>
<div class="right-content">
 <div style="position: fixed;z-index: 9;margin: 10px">
     <input type="text" title="{$setCenterPointWord}" placeholder="{$setCenterPointWord}" style="float: left;margin-right: 5px;padding-left: 5px;height: 27px;line-height: 27px;width: 300px" name="centerAddress">
     <input type="hidden" name="center_location" value="">
     <span class="spanButton li-btn-blue-bg" style="margin-top: 0;" id="setCenter">{$sureWord}</span>
</div>
 <div id="container" style="height: 730px"></div>
 <div class="sliderParent-div"><div id="sliderParent"></div>
</div>
</div>
</div>
{$style}
<script charset="utf-8" src="{$root}static/javascript/jackwei.slider.js?v=2"></script>
<script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&key={$key}"></script>
<script>
/**列表查询弹窗事件**/
$('.list-top').on('click', '.left-search', function (){
    $(this).find('.search-container').show();
})
$(document).on('click', '.layer_search_button,.cancel-button', function(event) {
    $(this).parents('.search-container').hide();
});
 $(function() {
        var center = new TMap.LatLng({$center});//设置中心点坐标
        //初始化地图
        var map = new TMap.Map("container", {
            center: center,
            zoom:12
        });
        map.setMapStyleId('style2');
        //初始化marker
        var marker = new TMap.MultiMarker({
            id: 'marker-layer',
            map: map,
            styles: {
                "marker": new TMap.MarkerStyle({
                    "width": 35,
                    "height": 35,
                    "anchor": { x: 16, y: 32 },
                    "src": '{$root}img/control/location_point.svg'
                }),
                "marker_center": new TMap.MarkerStyle({
                    "width": 15,
                    "height": 15,
                    "src": '{$root}img/control/map_center.svg'
                })
            },
            geometries: [{
                id: "map_center",
                styleId: 'marker',
                position: center,
                properties: {
                    title:'{$centerPointWord}'
                }
            }]
        });
//创建圆形覆盖物
var circle = new TMap.MultiCircle({
  map,
  styles: { // 设置圆形样式
	'circle': new TMap.CircleStyle({
	  'color': 'rgba(41,91,255,0.16)',
	  'showBorder': true,
	  'borderColor': 'rgba(41,91,255,1)',
	  'borderWidth': 2,
	}),
  },
  geometries: [{
    id:'range',
	styleId: 'circle',
	center: center, //圆形中心点坐标
	radius: 10000,	//半径（单位：米）
  }],
});
        var infoWindows = '';
        //监听回调函数（非匿名函数）
        var eventClick = function (evt) {
             if (evt.geometry){
                  // let pageX = evt.point.x;
                  // let pageY =evt.point.y;
                  let id = evt.geometry.id;
                  let location= new TMap.LatLng(evt.geometry.position.lat,evt.geometry.position.lng)
                  $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getSelectSet',{id:id},function(res) {
                        // $(body).append(res.data.html);
                                    //设置infoWindow
                            infoWindows = new TMap.InfoWindow({
                                map: map,
                                position: location,
                                content: res.data.html
                            });
                  },'json');
             }else{
                 infoWindows.close();
                 // $(".choiceDiv").remove()
             }
        }
            //监听marker点击事件
            // marker.on("hover", eventClick)
                 marker.on("click", eventClick)
            getMark();
        
            function getMark(){
                $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getMark',$("form[name='searchForm']").serialize(),function(res) {
                    $("#left-content-ul").empty().append(res.client);
                    if (!res.client){
                        $("#no-data-ico").css('display','block')
                    }else{
                         $("#no-data-ico").css('display','none')
                    }
                     let src = marker.getGeometries();
                      let removeIds = [];
                    $.each(src,function(index,value){
                              if ($.inArray(value.id,res.idCollection)==-1){
                                  removeIds.push(value.id);
                              }
                        });
                     marker.updateGeometries(eval(res.data));
                     marker.remove(removeIds);
                      marker.add({
                       id: "map_center",
                styleId: 'marker_center',
                position: center,
                properties: {
                           title:'{$centerPointWord}'
                }
                      });
                     //更新圆形覆盖
                     circle.updateGeometries(eval(res.range));

               },'json')
            }
            $("#searchButton").on('click',function() {
                 getMark();
            });

            var option = {
        color: '#629AFE',
        width: '400px',
        progress: 0.1,
        handleSrc: '../img/control/slider.svg',
        isCustomText: false,
        max:{$vicinityDistance},
    };
    $('#sliderParent')
        .jackWeiSlider(option)
        // .setText('2018-4-5 02:39:00')
        .setProgress(0.5)
        .setOnStartDragCallback(function () {

        })
        .setOnDragCallback(function (p) {

        })
        .setOnStopDragCallback(function (p) {
            $("[name='range']").val(p);
             getMark();
        });
     $("input[name='centerAddress']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=component&fun=getAddress',
        callback:function(data){
            $("[name='center_location']").val(data.location);
            let location = new TMap.LatLng(data.lat,data.lng);
            map.setCenter(location);//设置地图中心点
            // marker.remove([])
             marker.updateGeometries({
                       id: "map_center",
                styleId: 'marker_center',
                position: location,
                properties: {
                           title:'{$centerPointWord}'
                }
                })
        }
    });
     $("#setCenter").on('click',function (){
         let location = $("[name='center_location']").val();
         if (location){
             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=setCenter',{location:location},function (res){
                 if (res.warn==2){
                    window.location.reload();
                 }else{
                     msg(res.warn);
                 }
             },'json')
         }
     })
    })

</script>

efo;
        return $this->homeFun($html);
    }

    /**
     * 根据跟进时间
     */
    public function followText($followTime): string
    {
        $days = self::diffDays($followTime, $this->time);
        $text = '';
        if ($days <= 1) {
            $text = L('vicinityClient.followText.withinOneDay');
        } elseif ($days > 1 && $days <= 7) {
            $text = L('vicinityClient.followText.withinOneWeek');
        } elseif ($days > 7 && $days <= 30) {
            $text = L('vicinityClient.followText.withinOneMonth');
        } elseif ($days > 30 && $days <= 90) {
            $text = L('vicinityClient.followText.withinThreeMonth');
        } elseif ($days > 90) {
            $text = L('vicinityClient.followText.moreThanThreeMonths');
        }
        return $text;
    }

    /**
     * 设置地图中心点
     * @return bool|string
     */
    public function setCenter(): bool|string
    {
        $location = $this->post('location');
        if (empty($location)) {
            $json['warn'] = L('vicinityClient.setCenter.locationNotFound');
        } else {
            $json['warn'] = update(array('table' => 'para', 'field' => ['paValue' => $location], 'where' => "paid = 'centerPoint'"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}'], [$this->control['name'],$type], L('vicinityClient.setCenter.log')) . $location;
                $this->logText(["type" => self::page, "text" => $text]);
                $json['warn'] = 2;
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 样式
     * @return string
     */
    public function style(): string
    {
        return <<<eof
<style>
.sliderParent-div{position: absolute;right: 10px;bottom: 10px;z-index:  1000}
#sliderParent{padding: 50px;display: inline-block;}
.right-content{display: inline-block;width: 79%;}
.search-content{height: 50px;background-color: white}
.choiceDiv{text-align: left;padding: 0 10px;background-color: #FFFFFF;}
.left-content{display: inline-block;width: 19%;vertical-align: top;padding: 10px 5px;overflow: auto;max-height: 750px}
.left-content>ul>li{ width: 290px;height: 150px;background-color: white;margin: 10px 5px;border-radius: 5px;padding: 10px 5px;overflow: auto;}
.mark-show-content ul li{padding: 5px;}
.jws-outside-bar {width: 100%;height: 10px;background-color: white;border-radius: 3px;}
.jws-inside-bar {width: 0;height: 100%;border-radius: 3px;background-color: #629AFE;}

.jws-handle {
    height: 25px;
    width: 24px;
    margin-top: -17.5px;
    margin-left: -12px;
    display: block;
}

.jws-text {
    height: 30px;
    width: 80px;
    padding: 4px;
    color: black;
    margin-left: -40px;
    font-size: 14px;
    text-align: center;
    margin-top: -50px;
    font-weight: bold;
}
</style>
eof;

    }

    /**
     * 获取弹出层
     * @return bool|string
     */
    public function getSelectSet(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, "khid = '$id'");
        $center = explode(',', para('centerPoint'));
        $lat = $center[0];
        $lng = $center[1];
        $root = root;
        $dis = $this->unitChange(vicinityClientClass::getDistance($info['lat'], $info['lng'], $lat, $lng));
        //跟进天数
        $followText = $this->followText($info['lastFollowTime']);
        $json['data']['html'] = <<<efo
<div class="choiceDiv mark-show-content">
<ul>
<li><span style="font-weight: bold">{$info['companyName']}</span></li>
<li>{$info['workFlow']}&emsp;&emsp;{$followText}&emsp;&emsp;<img src="{$root}img/control/location.svg" style="width: 17px;height: 17px">{$dis}</li>
<li>{$info['address']}</li>
<li>{$info['contactName']}&emsp;&emsp;{$info['contactTel']}</li>
</ul>
</div>
efo;


        return json_encode($json, 320);
    }

    /**
     * 获取公司点标记
     */
    public function getMark(): bool|string
    {

        $root = root;
        $center = explode(',', para('centerPoint'));
        $lat = $center[0];
        $lng = $center[1];
        $client_li = '';
        $html = '[';
        $idCollection = [];
        //like查询数组
        $like = array(
            "tags" => $this->post('label'),//标签
            "companyName" => $this->post('companyName'),//客户名称
            "contactName" => $this->post('contactName'),//客户名称
            "contactTel" => $this->post('contactTel'),//联系手机
            "landline" => $this->post('landline'),//电话
            "text" => $this->post('text'),//备注
        );
        //全等查询数组
        $equal = array(
            'coid'=>self::$coid,
            "workFlow" => $this->post('workFlow'),//跟进情况
            "source" => $this->post('source'),//客户来源
        );
        //公私客
        $and = " and manager !='' and lng !=''";
        if ($this->post('time')) {
            $timeArr = explode(' ~ ', $this->post('time'));
            $and .= " and date(time) >='{$timeArr[0]}' and date(time) <='{$timeArr[1]}'";
        }
        if (!$this->power('client', "seeAll")) {
            //如果没有查看所有客户的权限
            $and .= " and see like '%" . $this->control['stid'] . "%' ";
        }
        if ($this->post('seeType') =='查看自己'){
            $and.=" and manager = '".self::$stid."'";
        }
        //范围
        $and .= $this->rangeWhere((float)$this->post('range'), $lng, $lat);
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;

        $result = find(array('table' => self::table, "where" => $where, "order" => "time desc"));
        $count=0;
        foreach ($result['array'] as $index => $array) {
            //距离
            $distance = vicinityClientClass::getDistance($array['lat'], $array['lng'], $lat, $lng);
            if ($distance > (float)$this->post('range')*1000){
                continue;
            }
            $count++;
            if ($index > 0) {
                $html .= ',';
            }
            $html .= <<<efo
            {
                "id": "{$array['khid']}",
                "styleId": 'marker',
                "position": new TMap.LatLng({$array['lat']}, {$array['lng']}),
                "properties": {
                    "title": "{$array['companyName']}",
                    'address':"{$array['address']}",
                    'contactName':"{$array['contactName']}",
                    'contactTel':"{$array['contactTel']}",
                    'lat':"{$array['lat']}",
                    'lng':"{$array['lng']}"
                }
            }
efo;


            $dis = $this->unitChange($distance);
            //跟进天数
            $followText = $this->followText($array['lastFollowTime']);
            //左边列表数据
            $client_li .= <<<eee

<li class="mark-show-content">
<ul>
<li><span style="font-weight: bold">{$array['companyName']}</span></li>
<li>{$array['workFlow']}&emsp;&emsp;{$followText}&emsp;&emsp;<img alt="" src="{$root}img/control/location.svg" style="width: 17px;height: 17px">{$dis}</li>
<li>{$array['address']}</li>
<li>{$array['contactName']}&emsp;&emsp;{$array['contactTel']}</li>
</ul>
</li>
eee;
            $idCollection[] = $array['khid'];
        }
        $json['data'] = $html . ']';
        $json['client'] = $client_li?("<span style='margin-left: 7px'>".str_replace(['{{count}}'], [$count], L('vicinityClient.getMark.client'))."</span>".$client_li):'';
        $json['idCollection'] = $idCollection;
        $meter = 1000 * $this->post('range');
        $json['range'] = <<<efo
[{
 id:'range',
	styleId: 'circle',
	center: center, //圆形中心点坐标
	radius: $meter,	//半径（单位：米）
  }]
efo;

        return json_encode($json, 320);
    }


    /**
     * 组成范围条件
     * @param $range
     * @param $lng
     * @param $lat
     * @return string
     */
    public function rangeWhere($range, $lng, $lat): string
    {
        $vicinityDistance = para('vicinityDistance');
        if ($range > 0) {
            if ($range > $vicinityDistance) {
                $range = $vicinityDistance;
            }
            //计算
            $location = self::getAround($lat,$lng,$range);

            $where = " and lng >= '{$location['minLng']}' and lng <= '{$location['maxLng']}' and lat >= '{$location['minLat']}' and lat <= '{$location['maxLat']}'";
        } else {
            $where = " and 1!=1";
        }
        return $where;
    }


    /**
     *计算某个经纬度的周围某段距离的正方形的四个点
     * @param float lng  经度
     * @param float lat  纬度
     * @param float distance  该点所在圆的半径，该圆与此正方形内切，单位米
     * @return array 正方形的四个点的经纬度坐标 lat >'$arr[minLat]' AND  lat <'$arr[maxLat]' AND lng >'$arr[minLng]' AND lng <'$arr[maxLng]'
     */
    public static function getAround($lat, $lon, $radius): array
    {
        $latitude = $lat;
        $longitude = $lon;
        $degree = (24901 * 1609) / 360.0;
        $radiusMile = $radius*1000;
        $dpmLat = 1 / $degree;
        $radiusLat = $dpmLat * $radiusMile;
        $minLat = $latitude - $radiusLat;
        $maxLat = $latitude + $radiusLat;
        $mpdLng = $degree * cos($latitude * (M_PI / 180));
        $dpmLng = 1 / $mpdLng;
        $radiusLng = $dpmLng * $radiusMile;
        $minLng = $longitude - $radiusLng;
        $maxLng = $longitude + $radiusLng;
        return array(
            'minLat' => $minLat,
            'maxLat' => $maxLat,
            'minLng' => $minLng,
            'maxLng' => $maxLng
        );
    }



    /**
     * 获取两个经纬度之间的距离
     * @param string $lat1 纬度1
     * @param string $lng1 经度1
     * @param string $lat2 纬度2
     * @param string $lng2 经度2
     * @return float 两件间的距离（米，保留一位小数）
     */
    public static function getDistance($lat1, $lng1, $lat2, $lng2): float
    {
        //将角度转为狐度
        $radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * self::EARTH_RADIUS;
        return round($s * 1000, 2);
    }

    /**
     * 单位转换
     * @param $meter
     * @return string
     */
    public function unitChange($meter): string
    {
        if ($meter >= 1000) {
            $meter = round($meter / 1000, 1) . 'km';

        } else {
            $meter = $meter . 'm';
        }
        return $meter;
    }
}
